//
//  BRRentOrderViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2025/01/27.
//  Copyright © 2025 Brezze GWG. All rights reserved.
//

#import "BRRentOrderViewController.h"
#import "BRAPI.h"
#import "BRRequestManager.h"
#import "BRHud.h"
#import "BRToolsView.h"
#import "BRTools.h"
#import "BROrderDetailViewController.h"
#import "BROrederListViewController.h"

@interface BRRentOrderViewController ()

@property (nonatomic,strong) QMUILabel *depositTitleLabel; // "押金充值"标题
@property (nonatomic,strong) QMUILabel *depositAmountLabel;
@property (nonatomic,strong) QMUILabel *depositTipLabel; // 说明文字
@property (nonatomic,strong) UIView *zalopayContainer;
@property (nonatomic,strong) UIImageView *zalopayRadio;
@property (nonatomic,strong) UIView *momopayContainer;
@property (nonatomic,strong) UIImageView *momopayRadio;
@property (nonatomic,strong) QMUIButton *payNowButton;
@property (nonatomic,strong) NSString *selectedPaymentMethod; // "zalopay" or "momo"
@property (nonatomic,strong) NSTimer *loadingTimer; // loading超时定时器
@property (nonatomic,strong) NSTimer *closePageTimer; // 支付后2分钟关闭页面定时器

@end

@implementation BRRentOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = Localized(@"rentOrder_title");
    self.selectedPaymentMethod = @"zalopay"; // 默认选择ZaloPay
    // 初始化押金金额为0，从接口获取真实值
    self.securityFee = 0.0;
    [self setUI];
    [self loadSecurityFeeConfig];
    
    // 监听支付完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePaymentCompleted:) name:@"BRPaymentCompleted" object:nil];
}

- (void)dealloc {
    // 移除通知监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // 取消定时器
    [self cancelLoadingTimer];
    [self cancelClosePageTimer];
}

/// 处理支付完成通知
- (void)handlePaymentCompleted:(NSNotification *)notification {
    NSLog(@"📍 [支付完成] 收到支付完成通知: %@", notification.userInfo);
    
    // 取消定时器
    [self cancelLoadingTimer];
    [self cancelClosePageTimer];
    
    // 隐藏loading
    UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
    [BRHud hiddenInView:parentView];
    
    // 恢复按钮状态
    self.payNowButton.enabled = YES;
    self.payNowButton.alpha = 1.0;
    
    NSLog(@"📍 [支付完成] 已隐藏loading并恢复按钮状态");
}

#pragma mark - UI Setup
- (void)setUI {
    self.view.backgroundColor = UIColor.qd_backgroundColor;
    
    // 顶部导航栏
    BRNavView *top = [self br_createTop:Localized(@"rentOrder_title")];
    top.mj_h = 134 + kSafeAreaTopHeight + 8 + 40 + 30; // 增加高度以容纳标题和说明文字
    top.popView.hidden = NO;
    
    // 修复约束冲突：确保BRNavView有正确的宽度约束
    [top mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
    }];
    
    // "押金充值"标题（黑色，大号字体）
    self.depositTitleLabel = [BRToolsView br_label:Localized(@"rentOrder_depositTitle") textColor:kColorTitle font:[UIFont fontB:20]];
    self.depositTitleLabel.textAlignment = NSTextAlignmentCenter;
    [top addSubview:self.depositTitleLabel];
    [self.depositTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(top.mas_top).offset(kSafeAreaTopHeight + 8 + 20);
    }];
    
    // 押金金额显示区域
    UIView *amountBg = [UIView new];
    [top addSubview:amountBg];
    [amountBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(76);
        make.left.offset(0);
        make.right.offset(0);
        make.top.equalTo(self.depositTitleLabel.mas_bottom).offset(12);
    }];
    
    // 分隔线（在说明文字下方）
    UIView *line = [BRToolsView getLineView:UIColorMakeWithHex(@"#D2D8E2")];
    line.alpha = 0.62;
    [top addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.bottom.offset(-66);
        make.left.offset(28);
        make.right.offset(-28);
    }];
    
    // 押金金额标签（橙色，大号字体）
    // 初始显示为空，等待接口返回后更新
    self.depositAmountLabel = [BRToolsView br_label:@"" textColor:UIColorMakeWithHex(@"#FF6B00") font:[UIFont fontB:37]];
    [amountBg addSubview:self.depositAmountLabel];
    [self.depositAmountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.centerY.offset(0);
    }];
    
    // 说明文字（在金额下方）
    self.depositTipLabel = [BRToolsView br_label:Localized(@"rentOrder_depositTip") textColor:UIColorMakeWithHex(@"#666666") font:[UIFont fontM:12]];
    self.depositTipLabel.numberOfLines = 0;
    self.depositTipLabel.textAlignment = NSTextAlignmentCenter;
    [top addSubview:self.depositTipLabel];
    [self.depositTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(amountBg.mas_bottom).offset(8);
        make.left.offset(28);
        make.right.offset(-28);
        make.bottom.equalTo(line.mas_top).offset(-8);
    }];
    
    // 调整顶部导航栏高度，容纳标题和说明文字
    top.mj_h = 134 + kSafeAreaTopHeight + 8 + 40 + 30; // 增加高度以容纳标题和说明文字
    
    // 内容区域
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = UIColor.qd_backgroundColor;
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(134 + kSafeAreaTopHeight + 8 + 40 + 30); // 增加高度以容纳标题和说明文字
    }];
    
    // 支付方式标题
    QMUILabel *paymentTitleLabel = [BRToolsView br_label:Localized(@"rentOrder_selectPaymentMethod") textColor:kColorTitle font:[UIFont fontB:16]];
    [contentView addSubview:paymentTitleLabel];
    [paymentTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(24);
        make.left.offset(20);
    }];
    
    // ZaloPay支付选项容器
    self.zalopayContainer = [[UIView alloc] init];
    self.zalopayContainer.backgroundColor = UIColorMakeWithRGBA(255, 247, 237, 1); // light orange background
    self.zalopayContainer.layer.cornerRadius = 8;
    self.zalopayContainer.layer.masksToBounds = YES;
    [contentView addSubview:self.zalopayContainer];
    [self.zalopayContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(paymentTitleLabel.mas_bottom).offset(16);
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_equalTo(64);
    }];
    
    // 添加点击手势
    UITapGestureRecognizer *zalopayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectZaloPay)];
    [self.zalopayContainer addGestureRecognizer:zalopayTap];
    
    // ZaloPay选项内容
    UIView *zalopayContent = [[UIView alloc] init];
    [self.zalopayContainer addSubview:zalopayContent];
    [zalopayContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(12, 16, 12, 16));
    }];
    
    // ZaloPay图标（可以使用文字代替）
    QMUILabel *zalopayIcon = [BRToolsView br_label:@"Z" textColor:UIColorMakeWithHex(@"#0068FF") font:[UIFont fontB:20]];
    zalopayIcon.backgroundColor = UIColorWhite;
    zalopayIcon.layer.cornerRadius = 20;
    zalopayIcon.textAlignment = NSTextAlignmentCenter;
    zalopayIcon.layer.masksToBounds = YES;
    [zalopayContent addSubview:zalopayIcon];
    [zalopayIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(40);
    }];
    
    // ZaloPay文字
    QMUILabel *zalopayLabel = [BRToolsView br_label:@"ZaloPay" textColor:kColorTitle font:[UIFont fontB:16]];
    [zalopayContent addSubview:zalopayLabel];
    [zalopayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zalopayIcon.mas_right).offset(12);
        make.centerY.offset(0);
    }];
    
    // ZaloPay单选按钮（选中状态）
    self.zalopayRadio = [[UIImageView alloc] init];
    self.zalopayRadio.image = [UIImage imageNamed:@"radio_selected"]; // 需要添加图片资源
    // 如果没有图片，使用自定义绘制
    if (!self.zalopayRadio.image) {
        self.zalopayRadio.image = [self createSelectedRadioImage];
    }
    [zalopayContent addSubview:self.zalopayRadio];
    [self.zalopayRadio mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(24);
    }];
    
    // MoMoPay支付选项容器
    self.momopayContainer = [[UIView alloc] init];
    self.momopayContainer.backgroundColor = UIColorClear;
    self.momopayContainer.layer.cornerRadius = 8;
    self.momopayContainer.layer.masksToBounds = YES;
    [contentView addSubview:self.momopayContainer];
    [self.momopayContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.zalopayContainer.mas_bottom).offset(12);
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_equalTo(64);
    }];
    
    // 添加点击手势
    UITapGestureRecognizer *momopayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectMoMoPay)];
    [self.momopayContainer addGestureRecognizer:momopayTap];
    
    // MoMoPay选项内容
    UIView *momopayContent = [[UIView alloc] init];
    [self.momopayContainer addSubview:momopayContent];
    [momopayContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(12, 16, 12, 16));
    }];
    
    // MoMoPay图标（可以使用文字代替）
    QMUILabel *momopayIcon = [BRToolsView br_label:@"M" textColor:UIColorMakeWithHex(@"#A50064") font:[UIFont fontB:20]];
    momopayIcon.backgroundColor = UIColorWhite;
    momopayIcon.layer.cornerRadius = 20;
    momopayIcon.textAlignment = NSTextAlignmentCenter;
    momopayIcon.layer.masksToBounds = YES;
    [momopayContent addSubview:momopayIcon];
    [momopayIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(40);
    }];
    
    // MoMoPay文字
    QMUILabel *momopayLabel = [BRToolsView br_label:@"MoMoPay" textColor:kColorTitle font:[UIFont fontB:16]];
    [momopayContent addSubview:momopayLabel];
    [momopayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(momopayIcon.mas_right).offset(12);
        make.centerY.offset(0);
    }];
    
    // MoMoPay单选按钮（未选中状态）
    self.momopayRadio = [[UIImageView alloc] init];
    self.momopayRadio.image = [self createUnselectedRadioImage];
    [momopayContent addSubview:self.momopayRadio];
    [self.momopayRadio mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(24);
    }];
    
    // 立即支付按钮
    self.payNowButton = [BRToolsView br_btnBGImg:Localized(@"rentOrder_payNow")];
    [contentView addSubview:self.payNowButton];
    [self.payNowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-(kSafeAreaBottomHeight + 20));
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_equalTo(52);
    }];
    [self.payNowButton addTarget:self action:@selector(handlePayment) forControlEvents:UIControlEventTouchUpInside];
    
    // 更新支付方式UI
    [self updatePaymentMethodUI];
}

#pragma mark - Request
/// 加载押金配置（获取真实押金金额）
- (void)loadSecurityFeeConfig {
    // 使用全屏loading
    UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
    [BRHud showInView:parentView];
    
    NSString *url = [BRAPI getSecurityPayConfig:self.powerBankType];
    
    [[BRRequestManager shared] GET:url params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        // 使用相同的view隐藏loading
        UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
        [BRHud hiddenInView:parentView];
        
        NSLog(@"📍 获取押金配置接口返回: %@", dataDict);
        
        // 解析响应数据 - 接口直接返回数据，结构为: {rentboxRuleConfig: {securityFee: 300000}}
        NSDictionary *rentboxRuleConfig = nil;
        
        // 先尝试从data字段获取
        if (dataDict[@"data"] && [dataDict[@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *data = dataDict[@"data"];
            rentboxRuleConfig = data[@"rentboxRuleConfig"];
        } else if (dataDict[@"rentboxRuleConfig"]) {
            // 接口直接返回，不包装在data中
            rentboxRuleConfig = dataDict[@"rentboxRuleConfig"];
        }
        
        if (rentboxRuleConfig && [rentboxRuleConfig isKindOfClass:[NSDictionary class]]) {
            // 获取押金金额（单位：分）
            id securityFeeObj = rentboxRuleConfig[@"securityFee"];
            CGFloat securityFee = 0;
            if ([securityFeeObj isKindOfClass:[NSNumber class]]) {
                securityFee = [securityFeeObj doubleValue];
            } else if ([securityFeeObj isKindOfClass:[NSString class]]) {
                securityFee = [securityFeeObj doubleValue];
            }
            
            NSLog(@"📍 解析到的押金金额: %.2f", securityFee);
            
            // 接口返回的securityFee就是真实的押金金额，直接使用
            // 格式化为越南盾显示时，每3位加一个点，去掉小数点后的无效0
            if (securityFee > 0) {
                self.securityFee = securityFee; // 保持为CGFloat，以便格式化函数处理小数
                NSLog(@"📍 押金金额: %.2f", securityFee);
                [self updateDepositAmountUI];
            } else {
                NSLog(@"⚠️ 押金金额为0或无效");
                self.securityFee = 0.0;
                [self updateDepositAmountUI];
            }
        } else {
            NSLog(@"⚠️ rentboxRuleConfig字段不存在或格式错误");
            self.securityFee = 0.0;
            [self updateDepositAmountUI];
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        // 使用相同的view隐藏loading
        UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
        [BRHud hiddenInView:parentView];
        NSLog(@"❌ 获取押金配置失败: code=%ld, msg=%@", (long)code, errMsg);
        // 接口失败时，不显示金额
        self.securityFee = 0.0;
        [self updateDepositAmountUI];
    }];
}

/// 更新押金金额UI显示
- (void)updateDepositAmountUI {
    if (self.securityFee > 0) {
        // 直接格式化securityFee，每3位加一个点，去掉小数点后的无效0
        NSString *amountStr = [BRTools br_formatVietnameseDong:self.securityFee];
        self.depositAmountLabel.text = [NSString stringWithFormat:@"%@₫", amountStr];
        self.depositAmountLabel.hidden = NO;
    } else {
        self.depositAmountLabel.text = @"";
        self.depositAmountLabel.hidden = YES;
    }
}

/// 创建选中状态的单选按钮图片
- (UIImage *)createSelectedRadioImage {
    CGSize size = CGSizeMake(24, 24);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 绘制外圆（蓝色）
    CGContextSetFillColorWithColor(context, UIColorMakeWithHex(@"#0068FF").CGColor);
    CGContextFillEllipseInRect(context, CGRectMake(0, 0, 24, 24));
    
    // 绘制内圆（白色）
    CGContextSetFillColorWithColor(context, UIColorWhite.CGColor);
    CGContextFillEllipseInRect(context, CGRectMake(3, 3, 18, 18));
    
    // 绘制中心点（蓝色）
    CGContextSetFillColorWithColor(context, UIColorMakeWithHex(@"#0068FF").CGColor);
    CGContextFillEllipseInRect(context, CGRectMake(9, 9, 6, 6));
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/// 选择ZaloPay支付方式
- (void)selectZaloPay {
    self.selectedPaymentMethod = @"zalopay";
    [self updatePaymentMethodUI];
}

/// 选择MoMoPay支付方式
- (void)selectMoMoPay {
    self.selectedPaymentMethod = @"momo";
    [self updatePaymentMethodUI];
}

/// 更新支付方式UI
- (void)updatePaymentMethodUI {
    if ([self.selectedPaymentMethod isEqualToString:@"zalopay"]) {
        self.zalopayContainer.backgroundColor = UIColorMakeWithRGBA(255, 247, 237, 1); // light orange
        self.zalopayRadio.image = [self createSelectedRadioImage];
        self.momopayContainer.backgroundColor = UIColorClear;
        self.momopayRadio.image = [self createUnselectedRadioImage];
    } else if ([self.selectedPaymentMethod isEqualToString:@"momo"]) {
        self.momopayContainer.backgroundColor = UIColorMakeWithRGBA(255, 247, 237, 1); // light orange
        self.momopayRadio.image = [self createSelectedRadioImage];
        self.zalopayContainer.backgroundColor = UIColorClear;
        self.zalopayRadio.image = [self createUnselectedRadioImage];
    }
}

/// 创建未选中状态的单选按钮图片
- (UIImage *)createUnselectedRadioImage {
    CGSize size = CGSizeMake(24, 24);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 绘制外圆（灰色边框）
    CGContextSetStrokeColorWithColor(context, UIColorMakeWithHex(@"#CCCCCC").CGColor);
    CGContextSetLineWidth(context, 2);
    CGContextStrokeEllipseInRect(context, CGRectMake(1, 1, 22, 22));
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/// 处理支付
- (void)handlePayment {
    // 显示全屏loading
    UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
    [BRHud showInView:parentView];
    
    // 置灰按钮
    self.payNowButton.enabled = NO;
    self.payNowButton.alpha = 0.5;
    
    // 启动定时器，10秒后自动取消loading（但保持按钮置灰）
    [self startLoadingTimer];
    
    // 启动关闭页面定时器，2分钟后自动关闭页面
    [self startClosePageTimer];
    
    // 直接打开浏览器访问H5支付页面
    [self launchPayment];
}

/// 启动支付（直接打开浏览器访问H5支付页面）
- (void)launchPayment {
    // 构建H5支付页面URL
    // 格式：http://localhost:8080/sw/app/callback_APP.html?type=ios&deviceId=deviceId&payType=zalo或momo
    NSString *baseUrl = @"https://s.youdianstar.com";
    
    // 根据选择的支付方式确定payType值
    NSString *payType = @"zalo"; // 默认zalo
    if ([self.selectedPaymentMethod isEqualToString:@"momo"]) {
        payType = @"momo";
    } else if ([self.selectedPaymentMethod isEqualToString:@"zalopay"]) {
        payType = @"zalo";
    }
    
    // 获取当前时间戳（秒）
    NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
    NSInteger timestampInt = (NSInteger)timestamp;
    
    // 构建基础URL（显示在地址栏的参数），添加时间戳避免重复跳转到同一个URL
    NSString *h5Url = [NSString stringWithFormat:@"%@/sw/app/callback_APP.html?type=ios&deviceId=%@&payType=%@&_t=%ld", baseUrl, self.deviceId ?: @"", payType, (long)timestampInt];
    
    // 将登录cookie等信息通过hash（#）传递，这样不会显示在地址栏，H5可以通过JavaScript读取
    // 使用Base64编码，避免明文显示
    NSMutableString *hashParams = [NSMutableString stringWithString:@"#"];
    
    // 从NSHTTPCookieStorage中读取所有cookie（后端可能使用cookie存储session/token）
    NSURL *cookieUrl = [NSURL URLWithString:baseUrl];
    NSArray<NSHTTPCookie *> *allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    
    NSLog(@"📍 [支付] 全局Cookie总数: %lu", (unsigned long)allCookies.count);
    
    // 查找与当前域名相关的cookie
    NSMutableArray<NSHTTPCookie *> *relevantCookies = [NSMutableArray array];
    for (NSHTTPCookie *cookie in allCookies) {
        // 检查cookie的domain是否匹配（localhost或相关域名）
        if ([cookie.domain containsString:@"localhost"] || 
            [cookie.domain containsString:@"youdian"] ||
            [cookie.domain containsString:@"youdianstar"]) {
            [relevantCookies addObject:cookie];
            NSLog(@"📍 [支付] 找到相关Cookie: %@ = %@ (domain: %@, path: %@)", 
                  cookie.name, 
                  cookie.value.length > 50 ? [cookie.value substringToIndex:50] : cookie.value,
                  cookie.domain,
                  cookie.path);
        }
    }
    
    // 如果有cookie，将所有cookie信息编码后传递
    if (relevantCookies.count > 0) {
        // 构建cookie字符串（格式：name1=value1;name2=value2）
        NSMutableString *cookieString = [NSMutableString string];
        for (NSInteger i = 0; i < relevantCookies.count; i++) {
            NSHTTPCookie *cookie = relevantCookies[i];
            if (i > 0) {
                [cookieString appendString:@";"];
            }
            [cookieString appendFormat:@"%@=%@", cookie.name, cookie.value];
        }
        
        // 将cookie字符串进行Base64编码
        NSData *cookieData = [cookieString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *encodedCookies = [cookieData base64EncodedStringWithOptions:0];
        
        // Base64编码可能包含+、/、=等特殊字符，需要进行URL编码
        NSString *urlEncodedCookies = [encodedCookies stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="].invertedSet];
        if (!urlEncodedCookies) {
            urlEncodedCookies = encodedCookies; // 如果编码失败，使用原始值
        }
        
        [hashParams appendFormat:@"cookies=%@", urlEncodedCookies];
        NSLog(@"📍 [支付] Cookie信息 - 原始长度: %lu, Base64编码后长度: %lu", (unsigned long)cookieString.length, (unsigned long)encodedCookies.length);
    }
    
    // 如果USERManager中有token，也传递（作为备用）
    if (USERManager.isLogin && USERManager.token.length > 0) {
        // 将token进行Base64编码
        NSData *tokenData = [USERManager.token dataUsingEncoding:NSUTF8StringEncoding];
        NSString *encodedToken = [tokenData base64EncodedStringWithOptions:0];
        
        // Base64编码可能包含+、/、=等特殊字符，需要进行URL编码
        NSString *urlEncodedToken = [encodedToken stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="].invertedSet];
        if (!urlEncodedToken) {
            urlEncodedToken = encodedToken; // 如果编码失败，使用原始值
        }
        
        if (hashParams.length > 1) {
            [hashParams appendString:@"&"];
        }
        [hashParams appendFormat:@"token=%@", urlEncodedToken];
        
        NSLog(@"📍 [支付] Token信息 - 原始长度: %lu, Base64编码后: %@", (unsigned long)USERManager.token.length, encodedToken.length > 50 ? [encodedToken substringToIndex:50] : encodedToken);
    }
    
    // 添加platform-id（如果有）
    NSString *platformId = nil;
    if (USERManager.loginTenantId.length != 0) {
        platformId = USERManager.loginTenantId;
    } else if (USERManager.tenantModel.platformId.length != 0) {
        platformId = USERManager.tenantModel.platformId;
    }
    if (platformId && platformId.length > 0) {
        if (hashParams.length > 1) {
            [hashParams appendString:@"&"];
        }
        [hashParams appendFormat:@"platformId=%@", platformId];
    }
    
    if (hashParams.length <= 1) {
        NSLog(@"⚠️ [支付] 没有找到任何cookie或token信息");
    }
    
    NSString *finalUrl = [NSString stringWithFormat:@"%@%@", h5Url, hashParams.length > 1 ? hashParams : @""];
    
    NSLog(@"📍 [支付] 准备打开H5支付页面: %@", h5Url);
    NSLog(@"📍 [支付] Hash参数（不显示在地址栏）: %@", hashParams.length > 1 ? hashParams : @"无");
    NSLog(@"📍 [支付] 完整URL（包含hash）: %@", finalUrl);
    
    NSURL *url = [NSURL URLWithString:finalUrl];
    if (!url) {
        // URL格式错误
        [self cancelLoadingTimer];
        UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
        [BRHud hiddenInView:parentView];
        self.payNowButton.enabled = YES;
        self.payNowButton.alpha = 1.0;
        NSLog(@"❌ 支付URL格式错误: %@", finalUrl);
        [BRHud showAuto:Localized(@"rentOrder_paymentLinkInvalid") inView:self.view];
        return;
    }
    
    // 直接打开系统浏览器（Safari）打开支付URL
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            // 打开支付URL后，保持loading和按钮置灰状态
            // 因为用户可能还在支付中，H5支付完成后会通过URL Scheme回调回来
            if (success) {
                NSLog(@"📍 已打开系统浏览器，H5支付页面: %@", h5Url);
                // 保持loading和按钮置灰，等待H5支付回调
            } else {
                NSLog(@"❌ 打开系统浏览器失败");
                // 失败时取消定时器、恢复按钮状态并隐藏loading
                [self cancelLoadingTimer];
                UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
                [BRHud hiddenInView:parentView];
                self.payNowButton.enabled = YES;
                self.payNowButton.alpha = 1.0;
                [BRHud showAuto:Localized(@"rentOrder_cannotOpenPaymentLink") inView:self.view];
            }
        }];
    } else {
        // 失败时取消定时器、恢复按钮状态并隐藏loading
        [self cancelLoadingTimer];
        UIView *parentView = [UIApplication sharedApplication].keyWindow ?: self.view;
        [BRHud hiddenInView:parentView];
        self.payNowButton.enabled = YES;
        self.payNowButton.alpha = 1.0;
        NSLog(@"❌ 支付链接无效: %@", finalUrl);
        [BRHud showAuto:Localized(@"rentOrder_paymentLinkInvalid") inView:self.view];
    }
}

#pragma mark - Loading Timer
/// 启动loading定时器（10秒后自动取消loading，但保持按钮置灰）
- (void)startLoadingTimer {
    // 先取消之前的定时器（如果存在）
    [self cancelLoadingTimer];
    
    // 创建定时器，10秒后触发
    __weak typeof(self) weakSelf = self;
    self.loadingTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            NSLog(@"⏰ [定时器] 10秒超时，自动取消loading（保持按钮置灰）");
            // 只隐藏loading，不恢复按钮状态
            UIView *parentView = [UIApplication sharedApplication].keyWindow ?: strongSelf.view;
            [BRHud hiddenInView:parentView];
            // 按钮保持置灰状态，不恢复
        }
    }];
}

/// 取消loading定时器
- (void)cancelLoadingTimer {
    if (self.loadingTimer) {
        [self.loadingTimer invalidate];
        self.loadingTimer = nil;
        NSLog(@"⏰ [定时器] 已取消loading定时器");
    }
}

/// 启动关闭页面定时器（2分钟后自动关闭页面）
- (void)startClosePageTimer {
    // 先取消之前的定时器（如果存在）
    [self cancelClosePageTimer];
    
    // 创建定时器，2分钟（120秒）后触发
    __weak typeof(self) weakSelf = self;
    self.closePageTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            NSLog(@"⏰ [定时器] 1分钟超时，自动关闭创建订单页面");
            // 在主线程关闭页面
            dispatch_async(dispatch_get_main_queue(), ^{
                [strongSelf.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
    
    NSLog(@"⏰ [定时器] 已启动关闭页面定时器，2分钟后自动关闭");
}

/// 取消关闭页面定时器
- (void)cancelClosePageTimer {
    if (self.closePageTimer) {
        [self.closePageTimer invalidate];
        self.closePageTimer = nil;
        NSLog(@"⏰ [定时器] 已取消关闭页面定时器");
    }
}




@end

